import numpy as np
from core.alogrithm import Algorithm
from collections import defaultdict

class FirstFitAlgorithm(Algorithm):
    ''':FirstFit
        当多个同时满足时，只选择第一个

    '''
    def __init__(self, threshold=0.8):
        self.threshold = threshold

    def __call__(self, board, clock):
        workers = board.ready_workers
        nodes = board.ready_nodes_which_has_waiting_task
        candidate_task = None
        candidate_worker = None
        all_candidates = dict()
        node_workes = defaultdict(list)

        for worker_idx in range(len(workers)):
            for node_idx in range(len(nodes)):
                # print(node.task.task_type,worker.skill_types)
                # todo: 需要node 排序，node結點個數相關信息
                # print("fit first algorithm")
                pointers = workers[worker_idx].accommodate(nodes[node_idx])

                if len(pointers) > 0 and not(node_idx in node_workes):
                    all_candidates[(worker_idx,node_idx)] = pointers[0]
                    # 直选择第一个作为匹配
                    node_workes[node_idx].append(worker_idx)
                    # 避免node--> worker
                    # worker-->node
                    break# 避免一个worker 对应多个node

        if len(all_candidates) == 0:
            return None, None,None

        candidate_worker = []
        candidate_node = []
        pointers = []
        for worker_idx,node_idx in all_candidates.keys():
            candidate_worker.append(workers[worker_idx])
            candidate_node.append(nodes[node_idx])
            pointers.append(all_candidates[(worker_idx,node_idx)])
        print("----------------------start")
        print("fit first algorithm")
        self.__debug(candidate_worker,candidate_node)

        print("----------------------end")
        return candidate_worker, candidate_node,pointers

    def __debug(self,candidate_worker,candidate_node):
        ''':arg打印分配信息'''
        print("--------start debug--------------")
        for i in range(len(candidate_node)):
            print(candidate_worker[i],"-->",candidate_node[i])

        print("--------end debug--------------")
